<template>
  <el-dialog :visible.sync="currentShowFlag" append-to-body fullscreen :close-on-click-modal="false" :close-on-press-escape="false" @open="handleDialogOpen" @closed="handleDialogClosed">
    <div slot="title" class="detail-dialog__header">{{$t('system_role.detailDialog')}}</div>
    <div>
      <simple-form ref="form" v-model="formModel" label-width="80px" :form-field="formField" :grid="{xs: 12, sm: 12, md: 8}" :view-flag="viewFlag"></simple-form>
      <el-tabs v-model="tabValue">
        <el-tab-pane :label="$t('system_role.tabTitle')" name="first">
          <el-tree ref="permissionTree" node-key="parentmenuid_menuid" :data="menuTreeData" :props="{ children: 'children', label: 'menuname' }" show-checkbox></el-tree>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div slot="footer">
      <el-button @click="handleDialogClose">{{$t('operation.cancel')}}</el-button>
      <el-button type="primary" @click="handleDataSubmit">{{$t('operation.submit')}}</el-button>
    </div>
  </el-dialog>
</template>
<script>
import Axios from 'axios'
const BASEURL = {
  update: '/Web/SysAdmin/ajax.html?sys_method=AddPromission&sys_objName=Sys_Menu',

  menu: '/Web/SysAdmin/ajax.html?sys_method=GetMenuAndAction&sys_objName=Sys_Menu',
  checkedMenu: '/Web/SysAdmin/ajax.html?sys_method=GetMenuIDsandActionIds'
}
export default {
  name: 'sys_role_authorization_detail',
  data () {
    return {
      tabValue: 'first',
      formModel: {},
      menuTreeData: [],
      checkedKeys: [],

      menu: []
    }
  },
  inject: ['handleDataSearch'],
  computed: {
    currentShowFlag: {
      get () { return this.showFlag },
      set (val) { this.$emit('update:showFlag', val) }
    },

    formField () {
      return [
        {
          prop: 'rolename',
          label: this.$t('system_role.name'),
          type: 'Input'
        },
        {
          prop: 'notes',
          label: this.$t('system_role.remarks'),
          type: 'Input',
          component: { type: 'textarea' },
          col: { xs: 24, sm: 24, md: 24 }
        }
      ]
    }
  },
  props: {
    showFlag: { type: Boolean, default: false },
    viewFlag: { type: Boolean },
    detailData: { type: Object },
    extData: { type: Object }
  },
  methods: {
    handleDialogClose () {
      this.currentShowFlag = false
    },

    handleDataSubmit () {
      let loadingFlag = this.$loading({ target: this.$el.querySelector('.el-dialog') })
      let param = { RoleID: this.detailData.roleid, sys_mid: this.extData.sys_mid, data: [] }

      let checkedNodes = this.$refs['permissionTree'].getCheckedNodes()
      let obj = {}
      checkedNodes.forEach(item => {
        if (item.children.length === 0) {
          obj[item.parentmenuid] = (obj[item.parentmenuid]) ? (`${obj[item.parentmenuid]},${item.menuid}`) : (`${item.menuid}`)
        }
      })
      for (let key in obj) {
        param.data.push({ MenuID: key, ActionIDs: obj[key] })
      }
      param.data = JSON.stringify(param.data)
      this.$axios
        .post(BASEURL.update, param)
        .then(resp => {
          this.currentShowFlag = false
          this.$message({ type: 'success', message: this.$t('tip.saveSuccess') })
          this.handleDataSearch()
        })
        .finally(() => {
          loadingFlag.close()
        })
    },

    handleDialogOpen () {
      this.formModel = Object.assign({}, this.formModel, this.detailData)

      let requestList = [this.$axios.post(BASEURL.menu, { RoleID: this.detailData.roleid, sys_mid: this.extData.sys_mid }), this.$axios.post(BASEURL.checkedMenu, { RoleID: this.detailData.roleid, sys_mid: this.extData.sys_mid })]
      let loadingFlag = this.$loading({ target: this.$el.querySelector('.el-dialog') })
      Axios
        .all(requestList)
        .then(Axios.spread((menu, checkedMenu) => {
          let menuArray = menu.rows
          menuArray.forEach(item => {
            item.parentmenuid_menuid = `${item.parentmenuid}_${item.menuid}`
          })
          this.menuTreeData = this.$utils.arrayToTree(menuArray)
          this.getCheckedKeys(checkedMenu)
        }))
        .finally(() => {
          loadingFlag.close()
        })
    },

    getCheckedKeys (checkedMenu) {
      let result = []
      for (let key in checkedMenu) {
        result.push(...checkedMenu[key].split(',').map(item => { return `${key}_${item}` }))
      }
      this.checkedKeys = result
      this.$refs['permissionTree'].setCheckedKeys(this.checkedKeys)
    },

    handleDialogClosed () {
      this.$refs.form.resetFields()
      this.menuTreeData.splice(0)
      this.tabValue = 'first'
      this.$refs['permissionTree'].setCheckedKeys([])
      this.formModel = {}
    }
  }
}
</script>
